let table = null;
let eData, dataCount;
let fileId = "";
let projectId = "";
layui
    .config({
        base: '../layui/exts/', //静态资源所在路径
    })
    .use(['table', 'form', 'dropdown', 'util'], function () {
        lui = layui;
        var form = layui.form, dropdown = layui.dropdown;
        $ = layui.$;
        form.render();

        dropdown.render({
            elem: '#filesBatchEdit'
            , trigger: 'hover'
            , data: [{
                title: '批量修改'
                , id: 'batchEdit'
            }, {
                title: '批量删除'
                , id: 'batchDel'
            }], click: function (obj, othis) {
                var data = table.checkStatus("fileDataTable").data;
                if (data.length === 0) {
                    top.parent.layer.alert("请选择需要处理的数据", {icon: 2});
                    return false;
                }
                var ids = [];
                for (let i = 0; i < data.length; i++) {
                    ids.push(data[i].id);
                }
                if (obj.id === 'batchEdit') {
                    batchModify("2", ids);
                } else if (obj.id === 'batchDel') {
                    batchDelete("2", ids);
                }
            }
        });
 
        dropdown.render({
            elem: '#recordBatchEdit'
            , trigger: 'hover'
            , data: [{
                title: '批量修改'
                , id: 'batchEdit'
            }, {
                title: '批量删除'
                , id: 'batchDel'
            }], click: function (obj, othis) {
                var data = table.checkStatus("dataRecordTable").data;
                if (data.length === 0) {
                    top.parent.layer.alert("请选择需要处理的数据", {icon: 2});
                    return false;
                }
                var ids = [];
                for (let i = 0; i < data.length; i++) {
                    ids.push(data[i].id);
                }
                if (obj.id === 'batchEdit') {
                    batchModify("1", ids);
                } else if (obj.id === 'batchDel') {
                    batchDelete("1", ids);
                }
            }
        });

        function batchModify(model, ids) {
            top.layer.open({
                type: 2,
                title: '批量修改档案信息',
                content: './collection/batchModify?archivesModel=' + model + '&fondsId=' + fondsID +
                    '&classifyId=' + classifyID + '&classId=' + classID + '&ids=' + ids.toString(),
                area: ['550px', '500px'],
                shadeClose: false,
                resize: false,
                btn: [
                    '<i class="layui-icon">&#xe605;</i> 确定',
                    '<i class="layui-icon">&#x1006;</i> 取消',
                ],
                yes: function (index, layero) {
                    var iframeWin = layero.find('iframe')[0];
                    if (iframeWin.contentWindow.Buttun_Submit()) {
                        table.reload('fileDataTable');
                    }
                },
                btn2: function (index) {
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                },
            });
        }

        function batchDelete(model, ids) {
            top.layer.confirm('确定要删除当前选择的数据吗？', function (index) {
                $.ajax({
                    url: '../collection/delArchives', //url
                    dataType: 'json', //数据格式
                    type: 'POST', //请求方式
                    async: false, //是否异步请求
                    data: {ids: ids.toString(), fondsId: fondsID, classId: classID, archivesModel: model},
                    success: function (result) {
                        if (result.code == 0) {
                            layer.close(index);
                            table.reload('fileDataTable');
                            top.parent.layer.msg(result.message, {icon: 1});
                        } else {
                            top.parent.layer.alert(result.message, {icon: 2});
                        }
                    },
                });
                return false;
            });
        }

        table = layui.table;
        let recordCols = []
        let recordCol = []
        $.ajax({
            type: 'POST',
            url: '/basic/getShowFieldList',
            dataType: "JSON",
            sync: false,
            data: {"classifyId": classId, "fillingModel": "1"},
            success: function (res) {
                recordCol.push({type: 'checkbox', fixed: 'left'});
                $.each(res.data, function (index, obj) {
                    let leftFixed = "";
                    if (obj.fixedLeft === "1") {
                        leftFixed = "left";
                    }
                    recordCol.push({
                        fixed: leftFixed,
                        field: obj.fieldName,
                        width: obj.showWidth,
                        title: obj.fieldTitle
                    });
                });
                recordCol.push({fixed: 'right', title: '操作', width: 110, toolbar: '#recordOperationBar'});
                recordCols.push(recordCol);
                openRecordData();
            }
        });

        let cols = []
        let col = []
        //案卷表格初始化
        $.ajax({
            type: 'POST',
            url: '/basic/getShowFieldList',
            dataType: "JSON",
            sync: false,
            data: {"classifyId": classId, "fillingModel": "2"},
            success: function (res) {
                col.push({type: 'checkbox', fixed: 'left'});
                col.push({fixed: 'left', field: 'entityStatus', title: '状态', width: 60, templet: '#entityStatusTpl'});
                col.push({fixed: 'left', field: 'status', title: '领卷', width: 50, templet: '#statusTpl'});
                col.push({fixed: 'left', field: 'batchCode', title: '接收批次号', width: 100,});

                $.each(res.data, function (index, obj) {
                    let leftFixed = "";
                    if (obj.fixedLeft === "1") {
                        leftFixed = "left";
                    }
                    col.push({fixed: leftFixed, field: obj.fieldName, width: obj.showWidth, title: obj.fieldTitle});
                });
                col.push({fixed: 'right', title: '操作', width: 90, toolbar: '#filesOperationBar'});
                cols.push(col);
                openFileData();
            }
        });


        function openFileData(value) {
            let data = {
                pid: pid,
                tid: tid,
                classifyId: classId
            };
            if (value !== undefined) {
                data["value"] = value;
            }
            let div = document.getElementById('fileData');
            let divHeight = div.clientHeight - 55;
            table.render({
                elem: '#fileDataTable',
                url: '../archives/getArchivesFile',
                contentType: 'application/json',
                method: 'post',
                cellMinWidth: 50,
                page: true,
                limit: 50,
                height: divHeight,
                loading: true,
                size: 'sm',
                where: data,
                cols: cols,
                done: function (res, curr, count) {
                    eData = res.data;
                    if (count === 0) {
                        fileId = "/";
                    }
                    //表格加载完成后，默认选中第一行
                    $('.layui-table-view[lay-table-id="fileDataTable"]').children(".layui-table-box").children(".layui-table-body").find('table tbody tr[data-index="0"]').click();
                },
            });
        }

        //监听选择行
        table.on("row(fileDataTable)", function (obj) {
            var data = obj.data;
            obj.tr.addClass("layui-table-click").siblings().removeClass("layui-table-click");
            fillingModel = data.fillingModel;
            fileId = data.id;
            openRecordData();
        });

        form.on('submit(fileSearch)', function (data) {
            value = data.field.value;
            openFileData(value);
            return false;
        });

        form.on('submit(recordSearch)', function (data) {
            value = data.field.value;
            openRecordData(value);
            return false;
        });

        //监听工具条
        table.on('tool(fileDataTable)', function (obj) {
            var data = obj.data;
            console.log(data)
            if (obj.event === 'edit') {
                top.layer.open({
                    type: 2,
                    title: '编辑档案信息',
                    content: './collection/setArchives?archivesModel=2&id=' + data.id + '&tid=' + tid +
                        '&classifyId=' + classId + '&pid=' + pid + '&fileId=' + fileId,
                    area: ['550px', $(top.window).height() + 'px'],
                    shadeClose: false,
                    resize: false,
                    offset: 'rt',
                    btn: [
                        '<i class="layui-icon">&#xe605;</i> 确定',
                        '<i class="layui-icon">&#x1006;</i> 取消',
                    ],
                    yes: function (index, layero) {
                        var iframeWin = layero.find('iframe')[0];
                        if (iframeWin.contentWindow.Buttun_Submit()) {
                            table.reload('fileDataTable');
                        }
                    },
                    btn2: function (index) {
                        layer.close(index); //如果设定了yes回调，需进行手工关闭
                    },
                });
            } else if (obj.event === 'del') {
                top.layer.confirm('确定要删除当前选择的案卷吗？', function (index) {
                    $.ajax({
                        url: '../collection/delArchives', //url
                        dataType: 'json', //数据格式
                        type: 'POST', //请求方式
                        async: false, //是否异步请求
                        data: {id: data.id, pid: pid, tid: tid, archivesModel: "2"},
                        success: function (result) {
                            if (result.code == 0) {
                                obj.del();
                                layer.close(index);
                                top.parent.layer.msg(result.message, {icon: 1});
                            } else {
                                top.parent.layer.alert(result.message, {icon: 2});
                            }
                        },
                    });
                    return false;
                });
            } else if (obj.event === 'downloadFiles') {
                $.ajax({
                    url: '../files/downloadFiles', //url
                    dataType: 'json', //数据格式
                    type: 'POST', //请求方式
                    async: false, //是否异步请求
                    data: {pid: data.id},
                    success: function (result) {
                        if (result.code === 0) {
                            top.parent.layer.msg(result.message, {icon: 1});
                            window.location.href = "../files/archives/downloadFiles?fileName=" + data.title + "&downLoadFile=" + result.data.file;
                        } else {
                            top.parent.layer.alert(result.message, {icon: 2});
                        }
                    },
                });
                return false;
            } else if (obj.event === 'changelog') {
                top.layer.open({
                    type: 2,
                    title: "档案追溯日志",
                    content: '../archives/changelog?archivesId=' + data.id,
                    area: ['500px', $(parent.window).height() + 'px'],
                    shadeClose: false,
                    resize: false,
                    offset: 'r',
                });
            }
        });

        function openRecordData(value) {
            let data = {
                classifyId: classId,
                pid: pid,
                tid: tid,
                parentId: fileId
            };
            if (value !== undefined) {
                data["value"] = value;
            }
            let div = document.getElementById('recordData');
            let divHeight = div.clientHeight - 47;
            let url = '../archives/getArchivesRecord';
            table.render({
                elem: '#recordDataTable'
                , url: url
                , contentType: 'application/json'
                , method: 'post'
                , cellMinWidth: 80
                , page: true
                , limit: 50
                , height: divHeight
                , loading: true
                , size: 'sm'
                , where: JSON.stringify(data)
                , cols: recordCols
                , done: function (res, curr, count) {
                    dataCount = count;
                    let eData = res.data;
                }
            });
        }

        form.on('submit(recordsSearch)', function (data) {
            rValue = data.field.value;
            openRecordData();
            return false;
        });


        //监听工具条
        table.on('tool(recordDataTable)', function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'edit':
                    top.layer.open({
                        type: 2,
                        title: '编辑档案信息',
                        content: './collection/setArchives?archivesModel=1&id=' + data.id +
                            '&classifyId=' + classifyId + '&pid=' + pid + '&tid=' + tid + '&fileId=' + fileId,
                        area: ['550px', $(top.window).height() + 'px'],
                        shadeClose: false,
                        resize: false,
                        offset: 'rt',
                        btn: [
                            '<i class="layui-icon">&#xe605;</i> 确定',
                            '<i class="layui-icon">&#x1006;</i> 取消',
                        ],
                        yes: function (index, layero) {
                            var iframeWin = layero.find('iframe')[0];
                            if (iframeWin.contentWindow.Buttun_Submit()) {
                                table.reload('recordDataTable');
                            }
                        },
                        btn2: function (index) {
                            layer.close(index); //如果设定了yes回调，需进行手工关闭
                        },
                    });
                    break;
                case 'del':
                    top.layer.confirm('确定要删除当前选择的文件吗？', function (index) {
                        $.ajax({
                            url: '../collection/delArchives', //url
                            dataType: 'json', //数据格式
                            type: 'POST', //请求方式
                            async: false, //是否异步请求
                            data: {id: data.id, pid: pid, tid: tid, archivesModel: "1"},
                            success: function (result) {
                                if (result.code == 0) {
                                    obj.del();
                                    layer.close(index);
                                    top.parent.layer.msg(result.message, {icon: 1});
                                } else {
                                    top.parent.layer.alert(result.message, {icon: 2});
                                }
                            },
                        });
                        return false;
                    });
                    break;
                case 'viewDigiFiles':
                    top.layer.open({
                        type: 2,
                        title: data.title + "  电子文件",
                        content: '../archives/archivesOriginalFiles?archivesId=' + data.id,
                        area: [$(top.parent.window).width() + 'px', $(top.parent.window).height() + 'px'],
                        shadeClose: false,
                        resize: false,
                        offset: 'r',
                    });
                    break;
                case  'changelog':
                    top.layer.open({
                        type: 2,
                        title: "档案追溯日志",
                        content: '../archives/changelog?archivesId=' + data.id,
                        area: ['500px', $(parent.window).height() + 'px'],
                        shadeClose: false,
                        resize: false,
                        offset: 'r',
                    });
                    break;
            }
        });
    });

function exportFileData() {
    table.exportFile("fileDataTable", eData, 'xls', "案卷目录");
}

function exportRecordsData() {
    fileExport(table, "dataRecordTable", "文件目录", dataCount, "allData")
}

function toProject() {
    let url = "?id=&fondsId=" + fondsID + "&classId=" + classID + "&classifyId=" + classifyID + "&fillingModel=" + fillingModel;
    location.href = "./fillingProject" + url;
}

function newFile() {
    top.layer.open({
        type: 2,
        title: '编辑档案信息',
        content: './collection/setArchives?archivesModel=2&pid=' + pid + '&tid=' + tid + '&classifyId=' + classifyId +
            '&projectId=' + projectId,
        area: ['550px', $(top.window).height() + 'px'],
        shadeClose: false,
        resize: false,
        offset: 'rt',
        btn: [
            '<i class="layui-icon">&#x1005;</i> 保存/新增',
            '<i class="layui-icon">&#xe605;</i> 确定',
            '<i class="layui-icon">&#x1006;</i> 取消',
        ],
        yes: function (index, layero) {
            var iframeWin = layero.find('iframe')[0];
            if (iframeWin.contentWindow.Buttun_SaveSubmit()) {
                table.reload('fileDataTable');
            }
        },
        btn2: function (index, layero) {
            var iframeWin = layero.find('iframe')[0];
            if (iframeWin.contentWindow.Buttun_Submit()) {
                table.reload('fileDataTable');
            } else {
                return false;
            }
        },
        btn3: function (index) {
            layer.close(index);
        },
    });
}

function filling() {
    var checkStatus = table.checkStatus('fileDataTable')
        , data = checkStatus.data;
    if (data.length == 0) {
        layer.msg("请选择需要归档的数据");
        return;
    }
    let ids = [];
    for (let i = 0; i < data.length; i++) {
        ids.push(data[i].id);
    }
    top.layer.confirm("确定所选择的案卷都归档码？", function (index) {
        $.ajax({
            url: './filesFilling', //url
            dataType: 'json', //数据格式
            type: 'POST', //请求方式
            async: false, //是否异步请求
            data: {fondsId: fondsID, classId: classID, status: 0, ids: ids.toString()},
            success: function (result) {
                if (result.code == 0) {
                    top.parent.layer.open({
                        icon: 1,
                        title: '提示信息',
                        content: result.message
                    });
                    table.reload('fileDataTable');
                    layer.close(index);
                } else {
                    top.parent.layer.alert(result.message, {icon: 2});
                }
            },
        });
        return false;
    });
}

function loadTemplate() {
    top.layer.confirm("载入模板将会清除现有的数据，确定要使用模板数据吗？", function (index) {
        $.ajax({
            url: './loadTemplateData', //url
            dataType: 'json', //数据格式
            type: 'POST', //请求方式
            async: false, //是否异步请求
            data: {pid: pid, tid: tid, fileId: fileId, classifyId: classifyId},
            success: function (result) {
                if (result.code == 0) {
                    top.parent.layer.alert(result.message, {icon: 1});
                    table.reload('dataRecordTable');
                    layer.close(index);
                } else {
                    top.parent.layer.alert(result.message, {icon: 2});
                }
            },
        });
        return false;
    });
}

function newRecords() {
    if (fileId == "") {
        top.parent.layer.alert("请选择需要增加文件的案卷", {icon: 2});
        return false;
    }
    top.layer.open({
        type: 2,
        title: '编辑档案信息',
        content: './collection/setArchives?archivesModel=1&pid=' + pid + '&classifyId=' + classifyId +
            '&tid=' + tid + '&fileId=' + fileId,
        area: ['550px', $(top.window).height() + 'px'],
        shadeClose: false,
        resize: false,
        offset: 'rt',
        btn: [
            '<i class="layui-icon">&#x1005;</i> 保存/新增',
            '<i class="layui-icon">&#xe605;</i> 确定',
            '<i class="layui-icon">&#x1006;</i> 取消',
        ],
        yes: function (index, layero) {
            var iframeWin = layero.find('iframe')[0];
            if (iframeWin.contentWindow.Buttun_SaveSubmit()) {
                table.reload('dataRecordTable');
            }
            return false;
        },
        btn2: function (index, layero) {
            var iframeWin = layero.find('iframe')[0];
            if (iframeWin.contentWindow.Buttun_Submit()) {
                table.reload('dataRecordTable');
            } else {
                return false;
            }
        },
        btn3: function (index) {
            layer.close(index); //如果设定了yes回调，需进行手工关闭
        },
    });
}

